<template>
  <el-dialog :visible="showDialog" :title="showTitle" @close="handleBtnCancel">
    <el-form ref="roleFormRef" label-width="120px" :model="formData" :rules="roleRules">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入角色名称" style="width: 80%" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="formData.description" placeholder="请输入角色描述" type="textarea" :rows="3" style="width: 80%" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-button size="small" @click="handleBtnCancel">取消</el-button>
        <el-button type="primary" size="small" @click="handleBtnOk">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { addRole, getRoleDetail, updateRole } from '@/api/setting'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        name: '',
        description: ''
      },
      roleRules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      }

    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑角色' : '新增角色'
    }
  },
  methods: {
    // 获取角色详情信息
    async getRoleDetail(roleId) {
      this.formData = await getRoleDetail(roleId)
    },
    handleBtnOk() {
      // 手动验证表单数据
      this.$refs.roleFormRef.validate(async isOk => {
        if (isOk) {
          if (this.formData.id) {
            await updateRole(this.formData)
            this.$message.success('保存成功')
          } else {
            await addRole(this.formData)
            this.$message.success('添加角色成功')
          }
          this.$emit('addRole')
          this.$emit('update:showDialog', false)
        }
      })
    },
    handleBtnCancel() {
      this.formData = {
        name: '',
        description: ''
      }
      this.$emit('update:showDialog', false)
      this.$refs.roleFormRef.resetFields()
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
